package com.xc.quickstart.common.context;


import com.alibaba.ttl.TransmittableThreadLocal;
import com.plumelog.core.TraceId;
import org.apache.commons.lang3.StringUtils;
import com.xc.quickstart.common.model.ApiContextModel;

import java.util.UUID;

public class ApiContext {
    private static ThreadLocal<ApiContextModel> threadLocal = new TransmittableThreadLocal<>();

    public static void setApiContextModel(ApiContextModel apiContextModel) {
        threadLocal.set(apiContextModel);
    }

    public static void removeApiContextModel() {
        threadLocal.remove();
        TraceId.logTraceID.remove();
    }

    public static ApiContextModel getOriginalApiContextModel() {
        return threadLocal.get();
    }

    public static ApiContextModel getApiContextModel() {
        ApiContextModel apiContextModel = threadLocal.get();

        if (null == apiContextModel) {
            setApiContextModel(new ApiContextModel());
        }
        return threadLocal.get();
    }

    public static String getCrmTraceId() {
        ApiContextModel apiContextModel = getApiContextModel();
        if (StringUtils.isEmpty(apiContextModel.getTraceId())) {
            String traceId = UUID.randomUUID().toString().replace("-", "");
            apiContextModel.setTraceId(traceId);
            //plumelog添加追踪码
            TraceId.logTraceID.set(traceId);
        }

        return apiContextModel.getTraceId();
    }
}
